from flask import render_template, request, jsonify, Response

from flask_cors import cross_origin
import requests
from app import app
from app.db.db_query import get_chat_session_list
from app.servers import get_chat_msg_by_flag, update_msg_text
from app.utils import get_str_md5


@app.route("/msg_v1/<int:mid>", methods=['GET'])
@cross_origin()
def msg_api(mid):
    # if mid != 17:
    #     return jsonify({"message": "无权限"})

    chat_session_list = get_chat_session_list()
    page = request.args.get("page", '1')

    page = int(page) if page.isdigit() else 1

    data = get_chat_msg_by_flag(chat_session_list[mid], page, order_by="DESC")

    return jsonify({"data": data[::-1]})


@app.route("/msg/<int:mid>/update-text", methods=['post'])
def update_text_api(mid):
    # 仅更改备份后的db文件
    chat_session_list = get_chat_session_list()

    mesLocalID = request.form['pk']
    msgContent = request.form['value']
    name_md5 = get_str_md5(chat_session_list[mid]["m_nsUsrName"])

    update_msg_text(name_md5, mesLocalID, msgContent)

    return jsonify({"message": "更新成功"})


@app.route("/<int:mid>", methods=['GET'])
def msg_index(mid):
    chat_session_list = get_chat_session_list()

    # return render_template('msg.html', chat_session_list=chat_session_list)
    return render_template('new_msg_v1.html', mid=mid, session=chat_session_list[mid])


@app.route("/")
def list_index():
    chat_session_list = get_chat_session_list()
    return render_template('index.html', chat_session_list=chat_session_list)


def get_content(url):
    res = requests.get(url)
    return res.content


@app.route("/img", methods=['GET'])
def img():
    url = request.args.get("url", '')
    img = get_content(url)
    resp = Response(img, mimetype="image/jpeg")
    return resp
